<template>
	<el-row >
		 <el-row>
			<el-col :lg='{span:20,offset:2}' align='left'>
				<el-tabs v-model="fir_activeName" >
	    			<el-tab-pane label="产品信息" name="first"></el-tab-pane>
	    		</el-tabs>
	    		<el-col :sm='16' :md='16' :lg='14'>
					<el-form ref="form" :model="form" label-width="150px" :label-position="labelPosition" size='small' class='form_auto' :rules='rules'  >
						<el-form-item label="产品名称：" prop='name'  >
						    <el-input v-model="form.name" placeholder='请输入产品名称'></el-input>
						</el-form-item>
						<el-form-item  class='rule_proName'>
						    <span>产品命名规则：产品类型-产品名称-发行人〈四个字以内的缩写〉-产品编号【示例：定项融资工具-恒悦俊-恒大-xxxxxx】</span>
						</el-form-item>

						<el-form-item label="产品类型："  prop='type' >
					  		<el-select v-model="form.type" placeholder="请选择" class='w-100'>
							    <el-option
							      v-for="item in pro_type"
							      :key="item.value"
							      :label="item.label"
							      :value="item.value">
							    </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="产品规模："  prop='size' >
						    <el-input v-model="form.size"  type='number'  class='number_right'><template slot="suffix">万元</template></el-input>
						</el-form-item>
						<el-form-item label="起投额："   >
						    <el-input v-model="form.startingAmt" type='number'  class='number_right'><template slot="suffix">万元</template></el-input>
						</el-form-item>
						<el-form-item      label="存续周期："  class='inline-block '  prop='subsistingCycle'>
		                    <el-input v-model="form.subsistingCycle" placeholder='请输入' class='w100'  type='number'></el-input>
		                    <el-select v-model="form.subsistingCycleUnit" placeholder="请选择" size='small' class='w100' >
		                        <el-option  
		                            v-for="item in chooseTime"
		                            :key="item.value"
		                            :label="item.label"
		                            :value="item.value">
		                        </el-option>
		                    </el-select>
			            </el-form-item>
			            <el-form-item label="所属项目：" prop='prjCode'  >
					    	<el-select v-model="form.prjCode" placeholder="请选择" class='w-100'  @change='(val)=>choosePro(val)' no-match-text='当前没有已过会的项目'>
							    <el-option
							      v-for="item in project_list"
							      :key="item.code"
							      :label="item.prjName"
							      :value="item.code">
							    </el-option>
							</el-select>
						</el-form-item>
			            <el-form-item      label="资金路径："  prop='collectionAmtType'>
		            		<!-- 需要加上el-group才可以通过验证 -->
		            		<el-radio-group  v-model="form.collectionAmtType" >
			                    <el-radio   label="2" >场外</el-radio>
			                    <el-radio   label="1" >场内</el-radio>
			                </el-radio-group>
			            </el-form-item>
			            <el-form-item label="交易所拟收费标准："  prop='chargesStandard'>
					    	<el-input  v-model="form.chargesStandard"  placeholder='请输入'  class='inline-block'><template slot="suffix">%</template></el-input>
					    	<el-radio  v-model="form.chargesMethod"  label="1" >年化收取</el-radio>
		                    <el-radio  v-model="form.chargesMethod"  label="2" >单笔收取</el-radio>
						</el-form-item>
						<el-form-item      label="收费方式："  >
							<el-radio-group v-model="form.chargingMethod">
							    	<el-radio    label="1" >前置</el-radio>
				                    <el-radio    label="2" >按季</el-radio>
				                    <el-radio    label="3" >按月</el-radio>
				                    <el-radio    label="4" >其他</el-radio>
						    </el-radio-group>
		                    <el-input v-show='form.chargingMethod==4'  v-model='form.chargingValue' placeholder='请输入'  ></el-input>
			            </el-form-item>
			            <el-form-item      label="产品兑付方式："   >
		            		<el-select v-model="form.cash"  placeholder="请选择"  class='w-100'  >
                                <el-option
                                  v-for="(item,index) in duifu_ways"
                                  :key="index"
                                  :label="item.name"
                                  :value="item.value">
                                </el-option>
                            </el-select>
			            </el-form-item>
			            <el-form-item      label="预计发行时间："  prop='estimatedReleaseTime'>
						    <el-date-picker
						      v-model="form.estimatedReleaseTime"
						      type="date"
						      placeholder="选择日期">
						    </el-date-picker>
			            </el-form-item>
			            <el-form-item   label='其他备注信息：'>
			              	<el-input v-model="form.comments" placeholder='请输入内容' type='textarea' rows='5' ></el-input>
			            </el-form-item>
						<el-form-item label="产品文件：" >
							<el-button type="primary" icon="el-icon-plus" size="small" round  @click="addFiles"  class='mb16'>添加</el-button>
							<el-table
                                :data="filelist"
                                header-row-class-name='bankheader' 
                                >
								<el-table-column  prop="fileName" label="描述"  align='center' ></el-table-column>
								<el-table-column   label="操作" align='center' width='150'>
								    <template v-slot="list">
								        <el-button  type="primary" size="mini" round @click="downloadFile( list.row.fileCode)">下载</el-button>
								        <el-button  type="danger"  size="mini" round @click="fileDelete( list.row.code)">删除</el-button>
								    </template>
								</el-table-column>
                            </el-table>
						</el-form-item>
					</el-form>
				</el-col>
			</el-col>
		</el-row>
		<el-row  class="text-center mt42">
            <el-button @click="common_goback()">取 消</el-button>
            <el-button type="primary" @click="submit('form')"  :loading='displayLoading'  >确 定</el-button>
        </el-row>
        <!-- 新增 文件 -->
        <FileEdit ref='addFile'  v-on:save='recept(arguments)'> </FileEdit>
	</el-row>	
</template>

<script >
/*interface*/
import { saveProduct,detailProduct,modifyProduct } from '@/api/professional_work/product/index'/*产品*/
import { listProject,detailProject  } from '@/api/professional_work/project/index'/*项目*/
/*components*/
import FileEdit  from '@/components/common/FileEdit'/*文件上传*/

export default {
	name: 'product_addNew',
	data(){
		/*交易所拟收费标准：*/
		let checkChargesStandard =(rule, value,  callback) => {
			        if(!this.form.chargesMethod){
			        	return callback(new Error('请选择收取方式'));
			        }
			        else{
			        	callback();
			        }
	    };
	    /*募集金额和募集路径*/
	    let checkCollectionAmtType =(rule, value,  callback) => {
			        if(!value){
			        	return callback(new Error('请选择收取方式'));
			        }
			        else{
			        	callback();
			        }
	    };
	    /*产品存续周期*/
	    let checkSubsistingCycle = (rule, value,  callback) => {
			        if(!this.form.subsistingCycleUnit){
			        	return callback(new Error('请输入产品存续周期，存续单位'));
			        }
			        else{
			        	callback();
			        }
	    };
		return {
			/*static*/
			fir_activeName:'first',
			//产品类型
			pro_type:[
                {value: '1',label: '收益权类'}, 
                {value: '2',label: '定向融资类'}, 
                {value: '3',label: '资产登记交易类'}, 
                {value: '4',label: '资产转让增值'},
                {value: '5',label: '其他类'}],
			//选择 月 年
		     chooseTime:[
		        {label:'日',value:'1'},
		        {label:'周',value:'2'},
		        {label:'月',value:'3'},
		        {label:'年',value:'4'},
		      ],
		      project_list:[],//项目列表
		      //标签列表
		      // options:[],
		      //兑付方式
		      duifu_ways:[
				{name:'年',value:'1'},
				{name:'半年',value:'2'},
				{name:'季度',value:'3'},
				{name:'自然季度',value:'4'},
				{name:'自然半年付息',value:'5'},
				{name:'一次性到期本息',value:'6'},
			],
			
      		labelPosition:'right',//label对齐方式

			/*active*/
			form:{
				collectionAmtType:'',
				chargesStandard:'',
				chargesMethod:'',
				chargingMethod:'',
				chargingValue:'',
			},
			rules:{
				name:[
					{required:true,message:'请输入产品名称'}
				],
				prjCode:[
					{required:true,message:'请选择所属项目'}
				],
				type:[
					{required:true,message:'请输入产品类型'}
				],
				size:[
					{required:true,message:'请输入产品规模'}
				],
				subsistingCycle:[
					{required:true,message:'请输入产品存续周期，存续单位'},
					{ validator: checkSubsistingCycle, trigger: 'blur' }
				],
				collectionAmtType:[
					{required:true,message:'请选择产品资金路径',trigger:'change'}
				],
				chargesStandard:[ //用于验证一个label验证两个必填项
      		 		{required:true,message:'请输入收费标准'},
      		 		{ validator: checkChargesStandard, trigger: 'change' }
      		 	],
      		 	estimatedReleaseTime:[
					{required:true,message:'请选择产品预计发行时间'}
				],
			},
			filelist:[],//产品文件

			/*编辑状态下当前产品code*/
			currentCode:'',//当前product  code
			isEdit:false,
			/*请求等待*/
			displayLoading: false,
			submitSuccess:false,//新增成功 编辑成功 =>清除缓存；取消编辑 返回上一页 =>仍然保持原页面

		}
	},
	created(){ 
		   //网页宽度判断，更改布局
		   let clientWidth = document.body.clientWidth
		    if(clientWidth<600){
		      this.labelPosition='top'
		    }

	      this.pageInit()
	      
	 },
	methods:{
		//初始化S
		async pageInit(){
	        let that =this,
	        	url='/op/project/get_project_list'
	        await listProject(url,{limit: 1000,currentPage:1,item_state:7}).then(res => {
				if(res.data.flag == true){
					this.project_list = res.data.dataList
				}
		      })
		      .catch(error => {
		            that.outputError(error)
		      })

		    // 编辑产品 --获取产品详情
		    if(this.$route.query.state == 'isEdit'){
		      		this.isEdit = true
		      		this.currentCode = this.$route.query.code
		      		// this.get_pro_detail(this.currentCode)
		      		await detailProduct(this.currentCode).then(res => {
				    	if(res.data.flag == true){
				    		this.form = res.data.data
				    		//产品文件回填
					        this.filelist = res.data.data.productFileList
				    	}
				    })
				    .catch(error => {
				            that.outputError(error)
				    })
		     }
	        
	    },
	    //初始化E

	    /*表单操作 submit & 关联项目相关信息 & 增删改操作 S*/
      	async submit(formName){
			let that =this
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.displayLoading = true
					/*文件处理*/
					this.form.productFileList = this.filelist

					if(this.isEdit == false){
							saveProduct(this.form).then(res=>{
								if(res.data.flag == true){
									this.submitSuccess = true
									this.$message({type:'success',message:res.data.msg})
			      					this.$router.push('/product')
								}
								setTimeout(function(){
			                        that.displayLoading = false
			                 	},500)
			      		})
			      		.catch(error=>{
							that.outputError(error)
			                setTimeout(function(){
			                    that.displayLoading = false
			                },500)
						})
					}
					else{
						modifyProduct(this.form).then(res=>{
							if(res.data.flag == true){
								this.submitSuccess = true
								this.$message({type:'success',message:res.data.msg})
		      					this.$router.push('/product')
							}
							setTimeout(function(){
		                        that.displayLoading = false
		                  	},500)
			      		})
			      		.catch(error=>{
							that.outputError(error)
							setTimeout(function(){
							      that.displayLoading = false
							},500)
						})
					}
				}
			})
      	},
      	//选择 关联项目相关信息
      	choosePro(val){
      		if(this.isEdit == false){
  				detailProject(val).then(res=>{
		       		if(res.data.flag == true){
		       			this.form.collectionAmtType = ''
		       			this.form.chargesStandard = ''
		       			this.form.chargesMethod = ''
		       			this.form.chargingValue = ''
		       			this.form.chargingMethod = ''

		       			this.form.collectionAmtType = res.data.data.collectionAmtType
		       			this.form.chargesStandard = res.data.data.chargesStandard
		       			this.form.chargesMethod = res.data.data.chargesMethod
		       			this.form.chargingValue = res.data.data.chargingValue
		       			this.form.chargingMethod = res.data.data.chargingMethod

		       		}
				})
	           .catch(error => {
		            this.outputError(error)
		        })
      		}
      	},
      	//新增文件
	    addFiles(){
	        this.$refs.addFile.$emit('openDialog')
	    },
	    //接收已经上传的文件，并返回列表
	    recept(arg){
	        let  form = arg[0] 
	        form.forEach((item,index)=>{
	          this.filelist.push({fileName:item.name,fileCode:item.code})
	        })
	    },
      	fileDelete(index,row){
      		this.common_del(index,this.filelist)
      	},
      	/*表单操作 submit & 关联项目相关信息 & 增删改操作 E*/
	},
	components:{
     	FileEdit,
    },
    beforeRouteLeave(to,from,next){
    	/*提交时不需缓存*/
     	from.meta.modifyCacheRoute = this.submitSuccess == true ? true :false
     	next()
    }
}
</script>

<style type="text/css" scoped>
/*名称规则命名*/
.rule_proName{color: #999;}	
</style>